﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services;
using MaterialDesignThemes.Wpf;
using System.ComponentModel.DataAnnotations;

namespace GameView.ViewModels
{
    public partial class BlacklistAddViewModel : ObservableValidator
    {
        private readonly BlacklistService _service;

        public BlacklistAddViewModel(BlacklistService service)
        {
            _service = service;
        }

        [Required(ErrorMessage = "机器码与提现账号不能全部为空！")]
        public string FullName => $"{NameCn}{NameEn}";

        [ObservableProperty]
        public string _tile = "新增黑名单";

        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(FullName))]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        public string _nameCn;

        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(FullName))]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        public string _nameEn;

        [ObservableProperty]
        public string _remark;

        [RelayCommand(CanExecute = nameof(CanSubmit))]
        private async Task Submit()
        {
            try
            {
                var dto = new Services.Dtos.Blacklist.BlacklistAddDto()
                {
                    NameEn = NameEn,
                    NameCn = NameCn,
                    Remark = Remark
                };
                var res = await _service.Add(dto);
                var isOK = res.StatusCode == 200;
                var msg = res.Errors;
                if (isOK)
                {
                    // 关闭弹窗
                    DialogHost.CloseDialogCommand.Execute(null, null);
                    GlobalMessage.Instance.ShowSuccess("操作成功！");
                }
                else
                {
                    GlobalMessage.Instance.ShowError(JSON.Serialize(msg));
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
        }

        private bool CanSubmit() => !HasErrors && (!NameCn.IsNullOrEmpty() || !NameEn.IsNullOrEmpty());
    }
}